package com.jarvis.pzz.modules.sourceshop;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.pzz.R;
import com.jarvis.pzz.common.BaseActivity;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.MyPublishShopsListModel;
import com.jarvis.pzz.modules.EditActivity;
import com.jarvis.pzz.modules.shop.view.ShopDetailsActivity;
import com.jarvis.pzz.modules.sourceshop.adapter.SourceShopAdapter;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.DividerItemDecoration;
import com.jarvis.pzz.util.net.RequestApi;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SourceShopActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.lin_title)
    RelativeLayout lin_title;
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.img_left)
    ImageView img_left;

    @BindView(R.id.recy_shop)
    RecyclerView recy_shop;
    @BindView(R.id.ptr_shop_source)
    PtrClassicFrameLayout ptr_shop_source;
    private SourceShopAdapter shopAdapter;

    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;
    private RequestService service;
    private List<MyPublishShopsListModel.shopPulishBaean> shopPulishBaeen;

    @Override
    public int getLayoutId() {
        return R.layout.activity_source_shop;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        shopPulishBaeen = new ArrayList<>();
        tv_title.setText("我发布的铺源");
        service = RequestApi.create(RequestService.class);
        setBar();
        setAdapter();
        setRefresh();
        setListener();
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_shop_source.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_shop_source.disableWhenHorizontalMove(true);
        ptr_shop_source.setLastUpdateTimeRelateObject(this);
        ptr_shop_source.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_shop, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_shop, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    getMyPublishShopsList();
                } else {
                    ptr_shop_source.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                shopAdapter.setNewData(new ArrayList<MyPublishShopsListModel.shopPulishBaean>());
                currentPage = 1;
                getMyPublishShopsList();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_left:
                finish();
                break;
        }
    }

    /**
     * 设置监听事件
     */
    public void setListener() {
        rel_left.setOnClickListener(this);
        recy_shop.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, final int i) {
                final MyPublishShopsListModel.shopPulishBaean shopListModel = shopAdapter.getData().get(i);
                LinearLayout ll_delete = (LinearLayout) view.findViewById(R.id.ll_delete);
                LinearLayout ll_source = (LinearLayout) view.findViewById(R.id.ll_source);
                ImageView im_modify = (ImageView) view.findViewById(R.id.im_modify);

                ll_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mActivity)
                                .setTitle("温馨提示")
                                .setMessage("是否删除:" + shopListModel.getShopTitle())
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        setDelShop(shopListModel.getShopId());
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        dialogBuilder.create().show();

                    }
                });
                ll_source.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyPublishShopsListModel.shopPulishBaean model = shopAdapter.getData().get(i);
                        if(model.getShopState().equals("1")) {
                            startActivity(new Intent(mActivity, ShopDetailsActivity.class).putExtra("shopId", model.getShopId()));
                        }else{
                            showTextToast("暂时不无法查看详情");
                        }
                    }
                });
                im_modify.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyPublishShopsListModel.shopPulishBaean model = shopAdapter.getData().get(i);
                        Intent intent = new Intent(SourceShopActivity.this, EditActivity.class);
                        intent.putExtra("SHOP",model);
                        startActivity(intent);
                    }
                });


            }

        });


    }


    /**
     * 设置adapter
     */
    public void setAdapter() {
        shopAdapter = new SourceShopAdapter(R.layout.item_source_shop, new ArrayList<MyPublishShopsListModel.shopPulishBaean>());
        recy_shop.setLayoutManager(new LinearLayoutManager(this));
        recy_shop.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        shopAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_shop.setAdapter(shopAdapter);
    }

    private void setBar() {
        lin_title.setVisibility(View.VISIBLE);
        lin_title.getBackground().setAlpha(255);
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(lin_title.getLayoutParams());
        lp.height=lp.height+statusBarHeight1;
        //lp.setMargins(0, statusBarHeight1, 0, 0);
        lin_title.setLayoutParams(lp);
        tv_title.setPadding(0, statusBarHeight1, 0, 0);
        rel_left.setPadding(0, statusBarHeight1, 0, 0);
        img_left.setPadding(0, statusBarHeight1, 0, 0);
    }

    private void getMyPublishShopsList() {

        Call<ResponseData<MyPublishShopsListModel>> myPublishShops = service.getMyPublishShopsList(String.valueOf(currentPage), String.valueOf(pageSize));
        myPublishShops.enqueue(new Callback<ResponseData<MyPublishShopsListModel>>() {
            @Override
            public void onResponse(Call<ResponseData<MyPublishShopsListModel>> call, Response<ResponseData<MyPublishShopsListModel>> response) {
                ptr_shop_source.refreshComplete();
                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        MyPublishShopsListModel myPublishShopsListModel = response.body().getData();
                        maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                        shopAdapter.addData(myPublishShopsListModel.getShopsList());
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData<MyPublishShopsListModel>> call, Throwable t) {
                ptr_shop_source.refreshComplete();
                showTextToast(RequestApi.detailError(t));
            }
        });

    }

    //删除铺源接口
    private void setDelShop(String shopId) {
        showDialog("loading");
        Call<ResponseData> responseDataCall = service.delShop(shopId);
        responseDataCall.enqueue(new Callback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                disMiss();
                if (response.body() != null) {
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        showTextToast("铺源删除成功");
                        shopAdapter.setNewData(new ArrayList<MyPublishShopsListModel.shopPulishBaean>());
                        currentPage = 1;
                        getMyPublishShopsList();
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                disMiss();
                showTextToast(RequestApi.detailError(t));
            }
        });
    }

    @Override
    public void onResume() {
        ptr_shop_source.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_shop_source.autoRefresh();
                    }
                }, 100);
        super.onResume();
    }
}
